package com.it.jwt.handler;

import com.it.common.domain.LoginUserDetails;
import com.it.common.utils.RedisCache;
import com.it.common.utils.Response;
import com.it.jwt.utils.JwtTokenHelper;
import com.it.jwt.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtTokenHelper jwtTokenHelper;

    @Resource
    private RedisCache redisCache;


    @Value("${jwt.tokenPrefix}")
    private String tokenPrefix;

    @Value("${jwt.tokenHeaderKey}")
    private String tokenHeaderKey;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 从 authentication 对象中获取用户的 UserDetails 实例，这里是获取用户的用户名
        LoginUserDetails loginUserDetails = (LoginUserDetails) authentication.getPrincipal();
        String username = loginUserDetails.getUsername();
        String password = loginUserDetails.getPassword();
        //<------判读用户是否登录或者没有过期防止重新登录------->
        // 从请求头中获取 key 为 Authorization 的值
        String header = request.getHeader(tokenHeaderKey);
        // 判断 value 值是否以 Bearer 开头
        if (StringUtils.startsWith(header, tokenPrefix)) {
            // 截取 Token 令牌
            String token = StringUtils.substring(header, 7);
            log.info("Token: {}", token);
            // 判空 Token
            if (StringUtils.isNotBlank(token)) {
                String key = "login:token"+token;
                // 从 Token 中解析出用户名
                String claims = "";
                try {
                    claims = jwtTokenHelper.getUsernameByToken(token);
                }catch (AuthenticationServiceException e){
                    log.info("{}",e);
                }
                System.out.println("claims: " + claims);
                if (StringUtils.isNotBlank(claims) && claims.equals(username)) {
                    redisCache.deleteObject(key);
                }
            }
        }
        //生成token
        String token = jwtTokenHelper.generateToken(username);
        String key = "login:token"+token;
        //TODO 存储到redis中
        redisCache.setCacheObject(key,loginUserDetails,1440, TimeUnit.MINUTES);
        // 返回 Token
        ResultUtil.ok(response, Response.success(token));

    }
}
